<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef"  :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目名称" prop="projectName">
        <el-input v-model="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="项目类型" prop="projectType">
        <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable style="width: 200px">
          <el-option v-for="dict in project_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item label="客户名称" prop="customerName">
        <el-input v-model="queryParams.customerName" placeholder="请输入客户名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <!-- <el-form-item label="当前阶段" prop="phaseCode">
        <el-input v-model="queryParams.phaseName" placeholder="请输入当前阶段" clearable @keyup.enter="handleQuery" />
      </el-form-item> -->
      <el-form-item label="预计验收日期" style="width: 308px">
        <el-date-picker v-model="daterangeAcceptTime" value-format="YYYY-MM-DD" type="daterange" range-separator="-"
          start-placeholder="开始日期" end-placeholder="结束日期"></el-date-picker>
      </el-form-item>
      <el-form-item label="立项金额">
        <div style="display: flex; align-items: center;">
          <el-input v-model="queryParams.minProjectAmount" placeholder="最小金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-right: 10px;" />
          -
          <el-input v-model="queryParams.maxProjectAmount" placeholder="最大金额" clearable @keyup.enter="handleQuery"
            style="width: 120px; margin-left: 10px;" />
        </div>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>

        <!-- <el-button type="primary" icon="Search" @click="handleSync">同步数据</el-button> -->
      </el-form-item>
    </el-form>
    <right-toolbar v-model:showSearch="showSearch"></right-toolbar>
    <div style="justify-content: flex-start;" v-if="userStore.name == 'xuhb'">
      <el-checkbox-group v-model="selectedProps">
        <el-checkbox v-for="col in allColumns" :key="col.prop" :label="col.prop">
          {{ col.label }}
        </el-checkbox>
      </el-checkbox-group>
      <el-button type="primary" plain style="margin: 10px;" @click="saveColumnConfig">保存配置</el-button>
    </div>
    <el-table v-loading="loading" :data="projectList" border>
      <el-table-column v-for="col in visibleColumns" :key="col.prop" :prop="col.prop" :label="col.label"
        :align="'center'"
        :show-overflow-tooltip="['contractAmount', 'settlementAmount', 'housekeeperName'].includes(col.prop)"
        :width="getWidth(col.prop)">
        <!-- 特殊列的插槽处理 -->
        <template #default="scope" v-if="['approvalDate', 'planDate', 'acceptTime'].includes(col.prop)">
          <span>{{ parseTime(scope.row[col.prop], "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>

      <!-- 固定操作列 -->
      <el-table-column label="操作" fixed="right" :width="userStore.isMobile ? 80 : 220"  align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="View" @click="handleView(scope.row)">查看</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改绩效基本信息对话框 -->
    <el-dialog fullscreen v-model="open" width="800px" append-to-body>
      <projectView :datas="form"  :key="form.projectNo" :column="3" :sizes="'large'"></projectView>


      <!-- 是否有 超级管理员 项目经理 销售 销售负责人 商务 财务权限之一  -->
      <div>
        <el-divider style="font-size: 16px; font-weight: bold;">项目质保信息</el-divider>
        <el-button :disabled="!addWarrantyPer"  type="primary" plain :icon="Plus" @click="addWarrantys()"
          style="margin-bottom: 10px;">添加质保信息</el-button>
        <el-table v-loading="loading" border :data="warrantyList" @selection-change="handleSelectionChange">
          <el-table-column label="付款单位" align="center" prop="company" />
          <el-table-column label="结算金额" align="center" prop="settlementAmount" />
          <!-- <el-table-column label="质保金比例(%)" align="center" prop="warrantyPercentage" /> -->
          <el-table-column label="质保金" align="center" prop="warranty" />
          <el-table-column label="质保金税率(%)" align="center" prop="rate">
            <template #default="scope">
              <dict-tag :options="warranty_rate" :value="scope.row.rate" />
            </template>
          </el-table-column>
          <el-table-column label="周期 周期(月)" align="center" prop="cycle" />
          <el-table-column label="起始日期" align="center" prop="startDate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.startDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="截止日期" align="center" prop="endDate" width="180">
            <template #default="scope">
              <span>{{ parseTime(scope.row.endDate, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column label="质保到期剩余(天)" align="center" prop="warrantyRemaining" />
          <el-table-column label="质保金实收金额" align="center" prop="receivedAmount" />
          <el-table-column label="操作人" align="center" prop="operator" />
          <!-- <el-table-column label="附件" align="center" prop="files" /> -->
          <!-- <el-table-column label="文件名称" align="center" prop="fileName" /> -->

          <!-- <el-table-column     label="文件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
          <template #default="scope" >
            <el-link :key="index" v-for="(file, index) in scope.row.files.split(',')" type="primary" @click="downloadFile(scope.row)">{{ scope.row.fileName }}</el-link>
          </template>
        </el-table-column> -->


          <el-table-column label="文件名称" align="center" show-overflow-tooltip width="200" prop="fileName">
            <template #default="scope">
              <div v-if="scope.row.files">
                <el-link v-for="(file, index) in scope.row.fileName.split(',')" :key="index" type="primary"
                  @click="downloadFile(scope.row,index,file)" style="display: block; margin-bottom: 5px;"
                  >
                  {{ file }}
                </el-link>
              </div>
              <div v-else>
                <!-- 无文件 -->
              </div>
            </template>
          </el-table-column>

          <el-table-column  v-if="finance" label="操作" align="center" fixed="right" width="220" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button link type="primary" :disabled="!addWarrantyPer" icon="Edit" @click="handleUpdateWarranty(scope.row)">修改</el-button>
              <el-button link type="primary" :disabled="!addWarrantyPer" icon="Delete" @click="handleDeleteWarranty(scope.row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="submitForm(1)">保存当前内容</el-button> -->
          <!-- <el-button type="primary" v-if="status == 1" @click="nextPhase()">下一步</el-button> -->
          <el-popconfirm v-if="status == 1 && haveNext" confirm-button-text="确认" cancel-button-text="取消" 
            title="确认提交到下一步?" @confirm="nextPhase" >
            <template #reference>
              <el-button type="primary" >下一步</el-button>
            </template>
          </el-popconfirm>
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog title="质保信息" v-model="openWarranty" width="700px" append-to-body>
      <el-form ref="warrantyRef" size="large" :model="warrantyForm" :rules="warrantyRules" label-width="160px">
        <el-form-item label="付款单位" prop="company">
          <el-input v-model="warrantyForm.company" placeholder="付款单位" />
        </el-form-item>
        <el-form-item label="结算金额" prop="settlementAmount">
          <el-input :disabled="true" v-model="warrantyForm.settlementAmount" placeholder="请输入结算金额" />
        </el-form-item>
        <!-- <el-form-item label="质保金比例(%)" prop="warrantyPercentage">
          <el-input type="number" @wheel.native.prevent @blur="handleBlur" v-model="warrantyForm.warrantyPercentage" placeholder="请输入质保金比例" />
        </el-form-item> -->
        <el-form-item label="质保金" prop="warrantyPercentage">
          <el-input type="number" @wheel.native.prevent :disabled="true" v-model="warrantyForm.warranty" placeholder="" />
        </el-form-item>
        <el-form-item label="质保金税率(%)" prop="rate">
          <el-select v-model="warrantyForm.rate" placeholder="请选择税率">
            <el-option v-for="dict in warranty_rate" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="周期(月)" prop="cycle">
          <el-input v-model="warrantyForm.cycle" placeholder="请输入周期(月)" />
        </el-form-item>
        <el-form-item label="质保开始日期" prop="startDate">
          <el-date-picker clearable v-model="warrantyForm.startDate" type="date" value-format="YYYY-MM-DD"
            placeholder="请选择起始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="质保金实收金额" prop="receivedAmount">
          <el-input v-model="warrantyForm.receivedAmount" placeholder="请输入质保金实收金额" />
        </el-form-item>
        <el-form-item label="质保金发票或收据" prop="files">
          <file-upload v-model="warrantyForm.files" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="warrantyForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitWarrantyForm">确 定</el-button>
          <el-button @click="cancelWarranty">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看 -->
    <el-dialog v-model="openView" fullscreen="" append-to-body>
      <el-tabs type="border-card" v-model="activeName"  @tab-click="handleClick">
        <el-tab-pane label="项目信息" name="first">
      <projectView :datas="form" :key="'projectView' + form.projectNo"  :isView="isView" :column="3" :sizes="'large'" :personList="personList"
        :attachmentList="attachmentList" :payList="payList" :accountingList="accountingList" :warrantyList="warrantyList" :implementList="implementList"></projectView>
    
      </el-tab-pane>
    <el-tab-pane label="正式清单" name="second">
      <mainList v-if="activeName == 'second'" :datas="form"></mainList>
    </el-tab-pane>
    <el-tab-pane label="管家婆出库单" name="third" >
      <saleList v-if="activeName == 'third'" :datas="form"></saleList>
    </el-tab-pane>
    <el-tab-pane label="费用汇总" name="four" >
      <feeList v-if="activeName == 'four'" :datas="form"></feeList>
    </el-tab-pane>
    <el-tab-pane label="清单对比" name="five">
          <compareMainAndSale v-if="activeName == 'five'" :datas="form"></compareMainAndSale>
        </el-tab-pane>
  </el-tabs>
        <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
  syncData,
  getCompanyList,
  getFinanceList,
  listParticipan, getParticipan, delParticipan, addParticipan, updateParticipan, getPermission,
  getStatus,listImplement ,saveUserTableConfig, getUserTableConfig
} from "@/api/project/project";
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment } from "@/api/project/project";
import {
  listPay, getTotalCost, listWarranty, getWarranty, delWarranty, addWarranty, updateWarranty,
  getPay, delPay, addPay, updatePay, listPhase, getPhase, delPhase, addPhase, updatePhase, listAccounting, getAccounting, delAccounting, addAccounting, updateAccounting
} from "@/api/project/project";
import {
  Plus
} from '@element-plus/icons-vue'
import { getInfo } from "@/api/login";
import { listAllUser, getUser, getPosts } from "@/api/system/user";

import { getCheck, getNextPermission, listDictionary, getDictionary, delDictionary, addDictionary, updateDictionary, listAllDictionary } from "@/api/project/dictionary";
const haveNext = ref(false)

const addPersonPer = ref(false)
const addFilePer  = ref(false)
const addPayPer = ref(false)
const addImplementPer  = ref(false)
const addWarrantyPer = ref(false)
const addAccountingPer = ref(false)
const loadingQuery = ref(false)
const cw = ref(false)
const allPer = ref(false)


const { proxy } = getCurrentInstance();
const { project_type } = proxy.useDict("project_type");
const { phase_type } = proxy.useDict("phase_type");
const { file_type } = proxy.useDict('file_type');
const { profit_type } = proxy.useDict('profit_type');
const { rate_type } = proxy.useDict('rate_type');
const { warranty_rate } = proxy.useDict('warranty_rate');
const attachmentList = ref([]);
const payList = ref([]);
const posts = ref([])
const userList = ref([])
const projectList = ref([]);
const personList = ref([]);
const companyList = ref([]);
const financeList = ref([]);
const accountingList = ref([]);
const implementList = ref([]);
const warrantyList = ref([]);
const open = ref(false);
const openView = ref(false);
const isView = ref(false);
const openOper = ref(false);
const openPhase = ref(false);
const openFile = ref(false);
const openWarranty = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeAcceptTime = ref([]);
const fileAccept = ref(["doc", "docx","cad","dwg", "xls", "ppt", "txt", "pdf", "xlsx", 'png', 'jpg', 'jpeg'],);
const projectNo = ref("")
const contractAmount = ref(0)
const settlementAmount = ref(0)
const materialCost = ref(0)
const companyId = ref('')
const company = ref('')
const finance = ref(false);//当期人员是否是财务
const isAdmin = ref(false);//是否是超级管理员
const havePay = ref(false);//是否有添加付款信息的权限
const status = ref("0");
const currenrPhaseId = ref()
const phasetList = ref([]);
const formDisabled = ref(true);
let currentPhase = reactive({
  phaseCode: '',
});


import projectView from "../projectView.vue";
import { ref } from "vue";
import { pa } from "element-plus/es/locale/index.mjs";
import { getToken } from "@/utils/auth";

const data = reactive({
  currentProject: {},
  form: {
    createUserName: null,
    createUserId: null,
    createDeptName: null,
    createDept: null,
  },
  currentConfig :{

  },
  personForm: {
  },
  fileForm: {

  },
  warrantyForm: {

  },


  queryParams: {
    pageNum: 1,
    pageSize: 10,
    status: 2,
    phaseId: 6,
    projectName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerName: null,
    housekeeperName: null,
    phaseCode: null,
    minProjectAmount: null,
    maxProjectAmount: null
  },
  rules: {
    projectName: [{ required: true, message: "项目名称不能为空", trigger: "blur" }],
    approvalDate: [{ required: true, message: "立项日期不能为空", trigger: "blur" }],
    projectType: [{ required: true, message: "项目类型 不能为空", trigger: "blur" }],
  },

  warrantyRules: {
    company: [{ required: true, message: "付款单位不能为空", trigger: "blur" }],
    settlementAmount: [{ required: true, message: "结算金额不能为空", trigger: "blur" }],
    // warrantyPercentage: [{ required: true, message: "质保金比例不能为空", trigger: "blur" }],
    settlementAmount: [{ required: true, message: "结算金额不能为空,请联系负责人在项目信息中填写结算金额", trigger: "blur" }],
  }


});


function handleBlur() {
    const percentage = parseFloat(warrantyForm.value.warrantyPercentage);
    console.log(`质保金比例: ${percentage}%`);
    // 计算金额并保留两位小数
    warrantyForm.value.warranty = parseFloat((percentage / 100 * warrantyForm.value.settlementAmount).toFixed(2));
    console.log(`计算后的金额为: ${warrantyForm.amount}`);
}

// import {getPermission} from "@/api/project/project";
async function downloadFile(row) {
  //只有项目经理 销售负责人 吴总 能够下载正式清单 竣工结算清单 正式合同
  if (row.attachmentType == '4' || row.attachmentType == '5' || row.attachmentType == '22') {
    let params = {
      projectNo: row.projectNo,
      postIds: [2, 5,6,7]//传入岗位id  项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
    }
    const res = await getPermission(params).then((response) => {
      console.log("下载附件", response.data);
      return response.data
    });
    if (!res) {
      proxy.$modal.msgError("暂无权限下载此附件");
      return
    }
  }

  var name = row.fileName;
  var url = row.filePath || row.files;
  // var suffix = url.substring(url.lastIndexOf("."), url.length);
  const a = document.createElement('a')
  a.setAttribute('download', name)
  a.setAttribute('target', '_blank')
  a.setAttribute('href', import.meta.env.VITE_APP_BASE_API + url)
  a.click()
}



import mainList from "../mainList.vue";
import saleList  from "../saleList.vue";
import feeList from "../fee.vue"
import compareMainAndSale from "../compareMainAndSale.vue"
const activeName = ref('first')
function handleClick(item,event){
  // activeName
  console.log("tabs页面跳转", item.paneName,event)
  activeName.value = item.paneName
}

/** 修改付款信息按钮操作 */
function handleUpdateWarranty(row) {
  resetWarranty();
  const _Id = row.id || ids.value
  getWarranty(_Id).then(response => {
    warrantyForm.value = response.data;
    openWarranty.value = true;
  });
}

// 获取文件名称
function getFileName(name) {
  // 如果是url那么取最后的名字 如果不是直接返回
  if (name.lastIndexOf("/") > -1) {
    return name.slice(name.lastIndexOf("/") + 1);
  } else {
    return name;
  }
}


/** 提交按钮 */
function submitWarrantyForm() {
  proxy.$refs["warrantyRef"].validate(valid => {
    if (valid) {
      warrantyForm.value.projectNo = projectNo.value
      warrantyForm.value.phaseId = 6
      // return
      if (warrantyForm.value.id != null) {
        updateWarranty(warrantyForm.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          openWarranty.value = false;
          getListParticipan(projectNo.value)
        });
      } else {
        addWarranty(warrantyForm.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          openWarranty.value = false;
          getListParticipan(projectNo.value)
        });
      }
    }
  });
}

/** 删除付款信息按钮操作 */
function handleDeleteWarranty(row) {
  const _Id = row.id
  proxy.$modal.confirm('是否确认删除？').then(function () {
    return delWarranty(_Id);
  }).then(() => {
    getListParticipan(projectNo.value)
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}




//添加付款信息 销售负责人添加付款信息？
function addWarrantys() {

  //校验是否是销售负责人？
  // //立项前期阶段 需要添加项目经理id 2 销售 9 商务 7 财务 6
  // result = attachmentList.value.find(item => item.postId === 2);
  //重置表单
  resetWarranty()
  // warrantyForm.value.projectAmount = contractAmount.value//合同签订金额自动带出 取结算金额？

  warrantyForm.value.settlementAmount = settlementAmount.value
  warrantyForm.value.company = company.value
  warrantyForm.value.companyId = companyId.value
  // personList.value = []
  openWarranty.value = true
  //项目立项前期 字典值为1 写死
  // const filteredObjects = phase_type.value.filter((obj) => obj.value == 1);
  // warrantyForm.value.phaseName = filteredObjects[0]?.label
  // warrantyForm.value.phaseId = filteredObjects[0]?.value

}


const { queryParams, form, personForm, payRules, warrantyRules, fileForm, warrantyForm,currentConfig  } = toRefs(data);


function getCurrUser(id) {
  getPosts(id).then(response => {
    console.log("66666666", response);
  });
}


//判断是否是销售负责人 项目经理 销售 财务 商务

async function isSale() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 5, 6, 7]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  havePay.value = await hasPermisson(params)
  console.log("添加付款信息", havePay.value);

}

//是否是财务
async function isFinance() {
  let params = {
    projectNo: projectNo.value,
    // phaseId: 1,//立项前期 写死
    postIds: [2, 6]//传入岗位id    需要添加项目经理id 2  销售负责人 5  销售 9 商务 7 财务 6
  }
  finance.value = await hasPermisson(params)

  console.log("添加财务信息", finance.value);
}

async function hasPermisson(params) {
  const res = await getPermission(params).then((response) => {
    console.log("权限信息", response.data);
    return response.data
  });
  return res
}


// function getPhaseStatus(){
//   getStatus
// }

function initData() {
  getUser().then(response => {
    posts.value = response.posts;
    console.log("岗位信息", response);
  });
  listAllUser().then(res => {
    console.log("userlist", res);
    userList.value = res
  });

  getInfo().then((res) => {
    console.log("当前用户", res);
    getCurrUser(res.user.userId)
  })
    .catch((error) => {
      console.log("error", error);
    });
}


/** 查询绩效基本信息列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeAcceptTime && "" != daterangeAcceptTime) {
    // queryParams.value.params["beginAcceptTime"] = daterangeAcceptTime.value[0];
    // queryParams.value.params["endAcceptTime"] = daterangeAcceptTime.value[1];
    queryParams.value.beginAcceptTime = daterangeAcceptTime.value[0];
    queryParams.value.endAcceptTime = daterangeAcceptTime.value[1];
  }
  listProject(queryParams.value).then((response) => {
    console.log("项目信息", response);
    projectList.value = response.data.rows;
    total.value = response.data.total;
    loading.value = false;
    console.log('projectList', projectList);

  });
}

// 取消按钮
function cancel() {
  open.value = false;
  openView.value = false
  reset();
}

// 取消按钮
function cancelWarranty() {
  openWarranty.value = false;
  resetWarranty();
}


//获取用户详细信息
function getUserInfo() {
  getInfo().then((res) => {
    const user = res.user;
    form.value.createUserName = user.nickName;
    form.value.createUserId = user.userId;
    form.value.createDeptName = user.dept.deptName
    form.value.createDept = user.deptId
    console.log("user", form);
  })
    .catch((error) => {
      console.log("error", error);
    });
}
// 表单重置
function reset() {
  form.value = {
    projectNo: null,
    projectName: null,
    createDeptName: null,
    projectAmount: null,
    projectType: null,
    projectUnit: null,
    acceptTime: null,
    customerAddress: null,
    customerName: null,
    housekeeperProject: null,
    phaseCode: null,
    remark: null,
    minProjectAmount: null,
    maxProjectAmount: null,
    companyName:null,
    companyType:null,
    companyNo:null
  };
  proxy.resetForm("projectRef");
}



// 表单重置
function resetWarranty() {
  warrantyForm.value = {
    // projectNo: null,
    // projectName: null,
    // createDeptName: null,
    // projectAmount: null,
    // projectType: null,
    // projectUnit: null,
    // acceptTime: null,
    // customerAddress: null,
    // customerName: null,
    // housekeeperProject: null,
    // phaseCode: null,
    // remark: null,
    // minProjectAmount: null,
    // maxProjectAmount: null
  };
  proxy.resetForm("warrantyRef");

}

/** 下载模板操作 */
function importTemplate() {
  proxy.download("project/attachment/importTemplate", {
  }, `user_template_${new Date().getTime()}.xlsx`);
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}


/** 重置按钮操作 */
function resetQuery() {
  daterangeAcceptTime.value = [];
  proxy.resetForm("queryRef");
  queryParams.value.minProjectAmount = null
  queryParams.value.maxProjectAmount = null
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.projectNo);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 新增按钮操作 */
function handleAdd() {
  formDisabled.value = false
  reset();
  personList.value = []
  open.value = true;
  title.value = "添加项目基本信息";
  form.value.startDate = getCurrentDateTime()
  form.value.approvalDate = getCurrentDate()
  getUserInfo()
}

/** 添加立项前期信息 */
function handleUpdate(row) {
  reset();
  isView.value = false
  const _projectNo = row.projectNo || ids.value;
  projectNo.value = row.projectNo //存放项目id
  contractAmount.value = row.contractAmount
  settlementAmount.value = row.settlementAmount
  company.value = row.housekeeperName
  companyId.value = row.housekeeperProject
  getProject(_projectNo).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改项目基本信息";
  });
  getListParticipan(row.projectNo)
  getNextPer(row.projectNo);
}


function getListParticipan(projectNo) {
  console.log("projectNoprojectNo", projectNo);

  let params = {
    projectNo: projectNo
  }
  //参与人
  listParticipan(params).then((response) => {
    console.log("参与人员", response);
    personList.value = response.data
  });

  //附件
  listAttachment(params).then((response) => {
    attachmentList.value = response.data;
  });

  //付款信息
  listPay(params).then((response) => {
    payList.value = response.data;
  });

  //核算信息
  listAccounting(params).then((response) => {
    accountingList.value = response.data;
  });

  //质保信息
  listWarranty(params).then((response) => {
    warrantyList.value = response.data;
  });


  listImplement(params).then((response) => {
    implementList.value = response.data;
  });


  isFinance()
  isSale()

  getCurrPhase(projectNo)

}


/** 阶段管理操作 */
async function handleView(row) {
    activeName.value = "first"
  formDisabled.value = true
  isView.value = true
  reset();
  getListParticipan(row.projectNo)
  const _projectNo = row.projectNo || ids.value;
  await getProject(_projectNo).then((response) => {
    form.value = response.data;
    openView.value = true;
  });


}



async function nextPhase() {
  //新版点击下一步 1.下一步按钮只开给需要审核的人 隐藏与显示 获取当前配置的环节规则 请求接口校验

  let params = {
    projectNo: projectNo.value,
    id: 6//项目质保
  }
  //校验该环节的所有配置
  const result = await getCheck(params).then(response => {//立项阶段 id写死
    console.log("项目实施校验", response);
    return response
  });
  if (result.data.permission == false) {
    proxy.$modal.msgError(result.data.message);
    return
  }
//校验通过 更新当前阶段信息

  let updateParams = {
    id: currenrPhaseId.value,
  }
 const updateResult =  await updatePhase(updateParams).then((response) => {
    console.log("更新阶段",response);
    return response
  });

  if(updateResult.data.status == 2){//如果该环节已完成 插入下一个环节
    let addParams = {
    projectNo: projectNo.value,
    phaseId: 7,//项目验收
  }
    addPhase(addParams).then((response) => {
      
    })
  }

  proxy.$modal.msgSuccess("提交成功");
  status.value = 2
  open.value = false
}

function getCurrPhase(projectNo) {
  let currPhase = {
    projectNo: projectNo,
    phaseId: 6//项目质保
  }
  getStatus(currPhase).then((response) => {
    console.log("当前阶段信息", response);
    if (response.data == null) {//没有查询到阶段信息  可以点击下一步 插入阶段信息
      //  currenrPhaseId.value = response.data.id
    } else {
      status.value = response.data.status
      currenrPhaseId.value = response.data.id
    }
  });
}


/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    "system/project/export",
    {
      ...queryParams.value,
    },
    `project_${new Date().getTime()}.xlsx`
  );
}

function getCurrentDateTime() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
};


function getCurrentDate() {
  const now = new Date();
  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0');
  const day = String(now.getDate()).padStart(2, '0');
  console.log("ssssssssssssssssss");
  // form.startDate =  `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  return `${year}-${month}-${day}`;
};

function getCurrPhaseConfig() {
  getDictionary(1).then(response => {//立项阶段 id写死 
    currentConfig.value = response.data;
  });
}

function getNextPer(projectNo) {
  let params = {
    projectNo: projectNo,
    id: 6//项目质保
  }
  getNextPermission(params).then(response => {//立项阶段 id写死
    console.log("项目前期 下一步权限", response);
    haveNext.value = response.data.permission

    addPersonPer.value = response.data.addPerson
    addFilePer.value = response.data.addFile
    addPayPer.value = response.data.addPay
    addImplementPer.value = response.data.addImplement
    addWarrantyPer.value = response.data.addWarranty
    addAccountingPer.value = response.data.addAccounting
    cw.value = response.data.cw
    allPer.value = response.data.admin

  });
}

getCurrPhaseConfig()

getList();
initData()



loadUserColumnConfig()


// 所有可用列配置（可从接口获取）
const allColumns = [
  { label: "项目名称", prop: "projectName", visible: true },
  { label: "发起人", prop: "createUserName", visible: true },
  { label: "合同金额", prop: "contractAmount", visible: true },
  { label: "结算金额", prop: "settlementAmount", visible: true },
  { label: "项目阶段", prop: "phaseName", visible: true },
  { label: "立项日期", prop: "approvalDate", visible: true },
  { label: "上次更新时间", prop: "updateTime", visible: true },
  { label: "预计验收日期", prop: "acceptTime", visible: true },
  { label: "客户名称", prop: "customerName", visible: true },
  { label: "管家婆项目", prop: "housekeeperName", visible: true },
  { label: "项目类型", prop: "projectTypeName", visible: true },
  { label: "阶段确认人", prop: "joinPeople", visible: true },
  { label: "当前操作人", prop: "currentPeople", visible: true },
]

// 用户当前选择的列 props（由 el-checkbox-group 控制）
const selectedProps = ref([])

// 当前可见列列表（根据 selectedProps 排序后的结果）
const visibleColumns = computed(() => {
  return selectedProps.value
    .map(prop => allColumns.find(col => col.prop === prop))
    .filter(Boolean)
})



// 当前可见列（根据用户选择动态变化）
const selectedColumns = ref([...allColumns])


const saveColumnConfig = async () => {

  console.log('保存配置', selectedProps.value);


  // 调用保存到后端的接口
  await saveUserTableConfig({ configs: selectedProps.value, type: "warranty" })
  proxy.$modal.msgSuccess("保存配置成功");

}

const getWidth = (prop) => {
  switch (prop) {
    case 'projectName':
    case 'approvalDate':
     case 'updateTime':
    case 'acceptTime':
      return 200;
    case 'housekeeperName':
      return 300;
    default:
      return undefined;
  }
}

async function loadUserColumnConfig() {
  const res = await getUserTableConfig({ type: "warranty" })

  let defaultOrder = allColumns
    .filter(col => col.visible !== false) // 可以根据 visible 控制是否默认显示
    .map(col => col.prop)

  if (res.data && Array.isArray(res.data)) {
    // 使用用户保存的顺序（只保留合法的 prop）
    selectedProps.value = res.data.filter(prop =>
      allColumns.some(col => col.prop === prop)
    )
  } else {
    // 否则使用默认顺序
    selectedProps.value = defaultOrder
  }
}

import useUserStore from '@/store/modules/user'

const userStore = useUserStore()
</script>
